using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace DataCapture.Helper;
/// <summary>
/// 配置文件工具类
/// </summary>
public static class ConfigurationHelper
{

    private static IConfigurationRoot _builder;
    private static PublicHelp.AppSettings _appSettings;
    private static void Init()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
            .AddJsonFile("appsettings.json", optional: false);//获取mian配置文件

        _builder = builder.Build();
        // 绑定配置到模型类
        _appSettings = _builder.Get<PublicHelp.AppSettings>();//转换为对象
    }
    /// <summary>
    /// 获取配置构建器
    /// </summary>
    /// <returns></returns>
    public static IConfigurationRoot GetBuilder()
    {
        if (_builder == null)
        {
            Init();
        }

        return _builder;
    }
    /// <summary>
    /// 根据名称，获取对应的配置信息
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static IConfigurationSection GetSession(string name)
    {
        return GetBuilder().GetSection(name);
    }
    /// <summary>
    /// 获取PLC配置信息
    /// </summary>
    /// <param name="plcName"></param>
    /// <returns></returns>
    public static PublicHelp.PlcServerConfig GetPlcServerConfig(string plcName)
    {
        // 获取所有 PLC 配置
        var plcServers = GetBuilder().GetSection("PlcServer")
            .Get<List<PublicHelp.PlcServerConfig>>();

        // 根据 plcName 过滤
        return plcServers?.FirstOrDefault(p => p.PlcName == plcName);
    }
    /// <summary>
    /// 获取PLC配置信息
    /// </summary>
    /// <param name="plcName"></param>
    /// <returns></returns>
    public static PublicHelp.PlcServerConfig GetPlcServerConfigList()
    {
        // 获取所有 PLC 配置
        var plcServerConfigList = GetBuilder().GetSection("PlcServer").Get<PublicHelp.PlcServerConfig>();
        return plcServerConfigList;
    }
    /// <summary>
    /// 获取APP配置表实体
    /// </summary>
    public static PublicHelp.AppSettings GetAppSettings
    {
        get
        {
            if (_appSettings == null)
            {
                Init();
            }

            return _appSettings;
        }
    }
}